import * as path from 'path';
import plugin from "../../../lib/plugins/plugin.js";
import common from '../../../lib/common/common.js'
import { MysApi } from '../model/bh3API.js';
import { getres } from '../model/bh3getr.js'; 
import { _path, pluginResources, pluginRoot } from "../model/path.js";
import { HID } from '../model/download.js';
import { getCache, upcache, downloadimage, createfold} from '../model/cache.js';
import { PAbyssR, uptime,bfbh,PGW,BVK} from '../model/bh3G.js';
import { bh3P,ABTA,BH3BF,BH3GW} from '../model/bh3P.js';
import {BH3UserInfo} from '../model/bh3uid.js';
import puppeteer from '../../../lib/puppeteer/puppeteer.js'
import NoteUser from "../../genshin/model/mys/NoteUser.js";
let a = `${pluginResources}/html/newbh3index/index.html`
let b = `${pluginResources}/html/newbh3index/index.css`
let c = `${pluginResources}/html/bh3index/index2.css`
let d = `${pluginResources}/html/vk/index.css`
const defaultImagePath = './plugins/qiqi-plugin/resources/BH3/404.png';
const defaultImagePath1 = './plugins/qiqi-plugin/resources/BH3/405.png';
const png404 = path.resolve(defaultImagePath);
const png405 = path.resolve(defaultImagePath1);
const cache = {}; 
let dataCQS;
let dataweek;
let datanb;
let databf;
let datagodwar;
let datavk;
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}


const arr2 =[
    { name: 'android01', alias: ['官', '安卓1', '安卓一', '国', '安卓国', '安卓官'] },  
    { name: 'bb01', alias: ['安卓2', '安卓二', 'b', 'B', 'bilibili', 'bili', '哔哩哔哩', 'b站',] },  
    { name: 'hun01', alias: ['安卓三', '安卓3', '华为', 'vivo', 'oppo', '渠道1', '渠道一', '渠道1服'] }, 
    { name: 'hun02', alias: ['小米', '360', '豌豆荚', '九游', '渠道2', '渠道二', '安卓四'] },
    { name: 'pc01', alias: ['桌面', '桌面服', '全平台', '全平台服', 'pc'] },
    { name: 'ios01', alias: ['ios', 'IOS', '苹果', 'apple', '果'] },
    { name: 'yyb01', alias: ['宝', '应用宝'] },
  ]
const arr3 =[
    { name: '安卓官服', alias: ['android01'] },  
    { name: '哔哩哔哩', alias: ['bb01'] },  
    { name: '渠道一服', alias: ['hun01'] }, 
    { name: '渠道二服', alias: ['hun02'] },
    { name: '桌面服·', alias: ['pc01'] },
    { name: '苹果服·', alias: ['ios01'] },
    { name: '应用宝·', alias: ['yyb01'] },
  ]

  
export class bh3 extends plugin {
    constructor() {
        super({
            name: 'bh3',
            dsc: 'bh3查询',
            event: 'message',
            priority: 1,
            rule: [
              {
                reg: "^崩三卡片(.*)$",
                fnc: 'bh3card'
              },
              {
                reg: "^崩三角色(.*)$",
                fnc: 'bh3role'
              },
              {
                reg: "^崩三绑定(.*)$",
                fnc: 'bh3bing'
              },

              {
                reg: "^(删除崩三绑定|崩三删除绑定|崩三删除)$",
                fnc: 'bh3del'
              },

              {
                reg: "^(崩三uid|崩三UID|崩三Uid)$",
                fnc: 'bh3uid'
              },

            ]
        })
    };
    async user () {
      return await NoteUser.create(this.e)
    }

    async bh3uid () {
        let msg = []
        let user = this.e.user_id
        const uid = await redis.get(`BH3:UID:${user}`);
        const server1 = await redis.get(`BH3:SERVER:${user}`);
        const foundItem = arr2.find(item => item.alias.includes(server1));
        const server = foundItem.name;
        console.log(uid)
        console.log(server)
        if (uid.length > 0) {
            msg.push(
            'uid为',
            uid,
            '服务器为',
            server
            )  
            await this.e.reply(await common.makeForwardMsg(this.e, [msg.join('\n')], '当前崩坏三绑定信息'))
        }else{
            e.reply(`当前账号无绑定uid服务器`);
       }
        

      }

    async bh3del(e) {
        let user = this.e.user_id
        let msg2;
        const uidKeys = await redis.keys(`BH3:UID:${user}`);
        const serverKeys = await redis.keys(`BH3:SERVER:${user}`);
        if (uidKeys.length > 0) {
              await redis.del(uidKeys);
              await redis.del(serverKeys);
              e.reply(`删除成功`);
        }else{
              e.reply(`当前账号无绑定uid服务器`);
        }
      }
  
      async bh3bing () {
        let user = this.e.user_id;
        let msg;
        let aaa = this.e.msg.replace("崩三绑定", "").trim();
        console.log(aaa);
        const matches = aaa.match(/^(\d{8,10})([^\d]+)?$/);
        if (!matches) {
            msg = [
                'UID 格式错误，请使用崩三绑定 xxx 服务器（崩三绑定111357883b）（官, 桌面, b, ios, 小米, 华为）。UID 必须为 8 到 12 位数字。',
            ];
            this.e.reply(msg);
            return true;
        }
        
        const uid = matches[1];
        const server = matches[2];
        console.log(uid);
        console.log(server);
        if (server) {
            await redis.set(`BH3:UID:${user}`, uid);
            await redis.set(`BH3:SERVER:${user}`, server);
            this.reply(`绑定成功 UID: ${uid}`, false);
        } else {
            msg = [
                '服务器为空，请使用崩三绑定xxx服务器(崩三绑定111357883b)(官,桌面,b,ios,小米,华为)',
            ];
            this.e.reply(msg);
            return true;
        }
    }

    async bh3role(){
      try {
        createfold()
        let userInput = this.e.msg.replace("崩三测试", "").trim();
        let inputUid = null;
        let inputServer = null;
        const matches = userInput.match(/^(\d{8,10})?([^\d]+)?$/);
        if (matches) {
          [, inputUid, inputServer] = matches;
        }
        const bh3UserInfo = new BH3UserInfo(this.e);
        const { uid, server, mysuid,ck } = await bh3UserInfo.getUserInfo(inputUid, inputServer);
        const bhapi = new MysApi(server, uid, mysuid);
        const bh3valkyrie = bhapi.valkyrie
        const bh3VK  = new getres(bh3valkyrie,server,uid,ck);
        const cachevk= getCache(uid, 'vk', './plugins/qiqi-plugin/data/BH3data/valkyrie');
        if (cachevk) {
          console.log('使用角色缓存数据');
          this.e.reply('使用角色缓存数据');
          datavk = cachevk;
        } else {
          const data = await bh3VK.fetchData();
          await upcache(uid, data, 'vk', './plugins/qiqi-plugin/data/BH3data/valkyrie');
          console.log('使用角色更新数据');
          this.e.reply('使用角色更新数据');
          datavk = data;
        }
        console.log(datavk)
        // const bhvk111 = await BVK(datavk);
        if (datavk.data) {
          const bhvk111 = await BVK(datavk);
          const html123 = await this.e.runtime.render('qiqi-plugin', `html/vk/index`, {
            save_id: uid,
            cards: bhvk111,
            d:d,
            uid:uid
          }, { scale: 1.4 });
        } else {
          this.e.reply("获取角色数据错误，请检查uid长度及服务器是否匹配");
        }

      } catch (error) {
        this.e.reply(error.message);
      }
    }

    async bh3card () {
      try {
      createfold()
      let userInput = this.e.msg.replace("崩三卡片", "").trim();
      let inputUid = null;
      let inputServer = null;
      const matches = userInput.match(/^(\d{8,10})?([^\d]+)?$/);
      if (matches) {
        [, inputUid, inputServer] = matches;
      }
      const bh3UserInfo = new BH3UserInfo(this.e);
      const { uid, server, mysuid,ck } = await bh3UserInfo.getUserInfo(inputUid, inputServer);
      const bhapi = new MysApi(server, uid, mysuid);
      const bh3index = bhapi.index;
      const bh3weekly= bhapi.weekly;
      const bh3newAbyss= bhapi.newAbyss;
      const bh3godWar1= bhapi.godWar;
      const bh3bf1= bhapi.battleField;
      const bh3getindex = new getres(bh3index,server,uid,ck);
      const bh3getweekly =new getres(bh3weekly,server,uid,ck)
      const bh3godWar= new getres(bh3godWar1,server,uid,ck);
      const bh3wnewAbyss= new getres(bh3newAbyss,server,uid,ck);
      const bhbf  = new getres(bh3bf1,server,uid,ck);
      const randomDelay = Math.floor(Math.random() * 2000) + 1000;
      await delay(randomDelay);
      const cachedData = getCache(uid, 'index', './plugins/qiqi-plugin/data/BH3data/index');
      if (cachedData) {
        console.log('使用缓存数据');
        this.e.reply('使用缓存数据');
        dataCQS = cachedData;
      } else {
        const data = await bh3getindex.fetchData();
        await upcache(uid, data, 'index', './plugins/qiqi-plugin/data/BH3data/index');
        console.log('使用更新数据');
        this.e.reply('更新中');
        dataCQS = data;
      }
      await delay(randomDelay);
      const cacheweeklyData = getCache(uid, 'weekly', './plugins/qiqi-plugin/data/BH3data/weekly');
      if (cacheweeklyData) {
        console.log('使用每周缓存数据');
        dataweek = cacheweeklyData;
      } else {
        const data = await bh3getweekly.fetchData();
        await upcache(uid, data, 'weekly', './plugins/qiqi-plugin/data/BH3data/weekly');
        console.log('更新每周数据中');
        dataweek = data;
      }
      await delay(randomDelay);
      const cachednewabyss = getCache(uid, 'newabyss', './plugins/qiqi-plugin/data/BH3data/newabyss');
      if (cachednewabyss) {
        console.log('使用深渊缓存数据');
        datanb = cachednewabyss;
      } else {
        const data = await bh3wnewAbyss.fetchData();
        await upcache(uid, data, 'newabyss', './plugins/qiqi-plugin/data/BH3data/newabyss');
        console.log('使用深渊更新数据');
        datanb = data;
      }
      await delay(randomDelay);
      const cachegodWar = getCache(uid, 'godWar', './plugins/qiqi-plugin/data/BH3data/godWar');
      if (cachegodWar) {
        console.log('使用乐土缓存数据');
        datagodwar = cachegodWar;
      } else {
        const data = await bh3godWar.fetchData();
        await upcache(uid, data, 'godWar', './plugins/qiqi-plugin/data/BH3data/godWar');
        console.log('使用乐土更新数据');
        datagodwar = data;
      }
      // await delay(randomDelay);
      // const cachevk= getCache(uid, 'vk', './plugins/qiqi-plugin/data/BH3data/valkyrie');
      // if (cachevk) {
      //   console.log('使用角色缓存数据');
      //   datavk = cachevk;
      // } else {
      //   const data = await bh3VK.fetchData();
      //   await upcache(uid, data, 'vk', './plugins/qiqi-plugin/data/BH3data/valkyrie');
      //   console.log('使用角色更新数据');
      //   datavk = data;
      // }
      await delay(randomDelay);
      const cachebf= getCache(uid, 'bf', './plugins/qiqi-plugin/data/BH3data/bf');
      if (cachebf) {
        console.log('使用战场缓存数据');
        databf = cachebf;
      } else {
        const data = await bhbf.fetchData();
        await upcache(uid, data, 'vk', './plugins/qiqi-plugin/data/BH3data/bf');
        console.log('使用战场更新数据');
        databf = data;
      }

      
      if (dataweek && dataweek.data) {
        let dataweekly = dataweek.data;
        const { month_hcoin, month_star, date } = dataweekly;
        let dataCQS1 = dataCQS.data;
        const { AvatarUrl, nickname, region, level } = dataCQS1.role;
        const iconpng1 = AvatarUrl.split('/').pop().split('.').shift();
        const icon_ava1 = await HID(iconpng1, AvatarUrl, './plugins/qiqi-plugin/resources/BH3/AvatarIcon');;
        const region1 = arr3.find(item => item.alias.includes(region)).name;
        const icon_ava2 =path.resolve(icon_ava1)
        const {
          active_day_number,
          sss_armor_number,
          god_war_max_challenge_score,
          armor_number,
          battle_field_ranking_percentage,
          suit_number,
          weapon_number,
          stigmata_number,
        } = dataCQS1.stats;
         
        let allAbyssData = [];
        let allbf = [];
        let allgw2 = [];
        const gwrd1 = datagodwar?.data?.records[0] || [];
        const gwicon1 = path.resolve('./plugins/qiqi-plugin/resources/html/bh3index/godwar.png')|| [];
        if (gwrd1.score) {
             const gwdata = await PGW(gwrd1);
             allgw2.push(gwdata);
        } else {
             console.warn(`数据缺少必要字段，已使用默认值。`);
             allgw2.push(BH3GW);
        }
        const bfReports = databf?.data?.reports || [];
        const bfdata1 = bfReports[0] ?? {};
        if (bfdata1.score) {
          const bfdata2 = await bfbh(bfdata1);
          allbf.push(bfdata2);
        } else {
            console.warn(`数据缺少必要字段，已使用默认值。`);
            allbf.push(BH3BF);
        }
       const abyssReports = datanb?.data?.reports || [];
       for (let i = 0; i < 3; i++) {
            const abyssR = abyssReports[i] ?? {};
         if (abyssR.boss) {
            const abyssData = await bh3P(abyssR);
         if (!abyssData.error) {
            allAbyssData.push(abyssData);
          }
      } else {
           console.warn(`第${i + 1}个数据缺少必要字段，已使用默认值。`);
           allAbyssData.push(ABTA); 
          }
      }

        const BH3 ={
               aau1: icon_ava2,
               nname: nickname,
               uuid: uid,
               llevel: level,
               sserver: region1,
               adn: active_day_number,
               sn1: suit_number,
               wn1: weapon_number,
               sn2: stigmata_number,
               sssan1: sss_armor_number,
               an1: armor_number,
               gwmcs: god_war_max_challenge_score,
               mh1: month_hcoin,
               ms1: month_star,
               dt1: date,
               allAbyssData,
               allbf,
               gwicon1,
               allgw2
            };
        const html1234 = await this.e.runtime.render('qiqi-plugin', `html/newbh3index/index`, {
              save_id: uid,
              BH3: BH3,
              a:a,
              b:b,
              c:c,
              uid:uid
            }, { scale: 1.4 });

    // let img= await puppeteer.screenshot("BH3", {                    
    //   tplFile: `${_path}/plugins/qiqi-plugin/resources/html/bh3index/index.html`,                 
    //   fullPage: true,
    //   quality:100,
    //   a:a,
    //   b:b,
    //   c:c,
    //   BH3
    //   });
    //   await this.reply(img)
    }
        return true;
       } catch (error) {
        this.e.reply(error.message);
       }

  }
}
  


   
